package com.cy.predicate;

import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
@Component
public class PageRoutePredicateFactory
        extends AbstractRoutePredicateFactory<PageRoutePredicateFactory.Config> {
    public PageRoutePredicateFactory(){
        super(Config.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("minPage", "maxPage");
    }

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        return new Predicate<ServerWebExchange>() {
            @Override
            public boolean test(ServerWebExchange serverWebExchange) {
                String pageStr=
                    serverWebExchange.getRequest().getQueryParams().getFirst("Page");
                Integer page=Integer.parseInt(pageStr);
                return page>config.getMinPage()&&page<config.getMaxPage();
            }
        };
    }

    public static class Config{
        private Integer minPage;
        private Integer maxPage;

        public Integer getMinPage() {
            return minPage;
        }

        public void setMinPage(Integer minPage) {
            this.minPage = minPage;
        }

        public Integer getMaxPage() {
            return maxPage;
        }

        public void setMaxPage(Integer maxPage) {
            this.maxPage = maxPage;
        }
    }
}
